﻿using System;
using System.Collections.Generic;
using System.IO;
using EmployeeApp.DAL.Dal;
using EmployeeApp.DAL.Entities;
using EmployeeApp.DAL.Models.Branch;
using EmployeeApp.Service.Dto.Branch;
using EmployeeApp.Service.Dto.Employee;
using EmployeeApp.Service.Dto.Position;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace EmployeeApp.Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BranchService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BranchService.svc or BranchService.svc.cs at the Solution Explorer and start debugging.
    public class BranchService : IBranchService
    {
        public ISession Session;
        readonly ISessionFactory _sessionFactory;
        public BranchService()
        {
            var appReader = new System.Configuration.AppSettingsReader();
            var connectionString = Convert.ToString(appReader.GetValue("connectionString", typeof(string)));
            var mappingScriptPath = AppDomain.CurrentDomain.BaseDirectory + "/db_mappings";
            if (!Directory.Exists(mappingScriptPath))
                Directory.CreateDirectory(mappingScriptPath);

            _sessionFactory = Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008
                    .ConnectionString(@connectionString))
                    .Mappings(x => x.AutoMappings.Add(AutoMap.AssemblyOf<Branch>().Where(t => t.Namespace.EndsWith("Entities"))).ExportTo(@mappingScriptPath))
                //.ExposeConfiguration(BuildSchema) // ********** ใช้ครั้งแรกเท่านั้น (กรณียังไม่มี Table)
                    .BuildSessionFactory();
            Session = _sessionFactory.OpenSession();
        }
        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(false, true);
        }

        public Dto.Branch.ResponseDto<List<BranchDto>> GetAll(Dto.Branch.GetAllRequestDto arg)
        {
            var result = new Dto.Branch.ResponseDto<List<BranchDto>>();
            try
            {
                var dal = new BranchDAL(Session);

                SearchCriteria search = null;
                if (arg != null)
                {
                    search = new SearchCriteria
                                 {
                                     Code = arg.Code,
                                     Name = arg.Name,
                                     Sort = arg.Sort,
                                     SortType = arg.SortType,
                                 };
                }

                var list = dal.GetAll(search);
                result.Data = new List<BranchDto>();
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        var obj = new BranchDto();
                        obj.Id = item.Id;
                        obj.Code = item.Code;
                        obj.Name = item.Name;
                        obj.Fax = item.Fax;
                        obj.Phone = item.Phone;
                        obj.Employees = new List<EmployeeDto>();
                        if (null != item.Employees)
                        {
                            foreach (var emp in item.Employees)
                            {
                                var dto = new EmployeeDto();
                                dto.Id = emp.Id;
                                dto.Hired = emp.Hired;
                                dto.Title = emp.Title;
                                dto.Name = emp.Name;
                                dto.EmpId = emp.EmpId;
                                dto.Status = emp.Status;
                                dto.Surname = emp.Surname;
                                dto.Address = emp.Address;
                                dto.JobTitle = new PositionDto();
                                if (null != emp.JobTitle)
                                {
                                    dto.JobTitle.Code = emp.JobTitle.Code;
                                    dto.JobTitle.Id = emp.JobTitle.Id;
                                    dto.JobTitle.Name = emp.JobTitle.Name;
                                }
                                dto.BirthDate = emp.BirthDate;
                                dto.MarriedStatus = emp.MarriedStatus;
                            }
                        }

                        result.Data.Add(obj);
                    }
                }
                result.Status = true;
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }
    }
}
